package com.uenpay.util.xml;

import android.util.Log;
import android.util.Xml;

import com.socks.library.KLog;

import org.xmlpull.v1.XmlPullParser;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Pull 解析规律列表 xml
 */
public class PullParser {

	private static final String TAG = "PullParser";

	public PullParser() {

	}

	/**
	 * @param result 输入 xml 字符串
	 * @param params xml节点数组
	 * @return
	 */
	public static List<Map<String, String>> parser(String result, String[] params) {
		if (result == null || params == null) {
			return null;
		}

		List<Map<String, String>> list_map = new ArrayList<Map<String, String>>();
		Map<String, String> string_map =  null;
		String temp_string = "";

		try {
			InputStream inputStream = new ByteArrayInputStream(result.getBytes("UTF-8"));
			XmlPullParser pullParser = Xml.newPullParser();
			pullParser.setInput(inputStream, "UTF-8");
			int event = pullParser.getEventType();

			while (event != XmlPullParser.END_DOCUMENT) {
				switch (event) {

				case XmlPullParser.START_DOCUMENT:
					break;

				case XmlPullParser.START_TAG:

					String name_tag = pullParser.getName();
					if ("TRANDETAIL".equals(name_tag)) {
						string_map = new LinkedHashMap<String, String>();
//						pullParser.getAttributeValue(0);
					} else if ("ORGPOSTERIMAGE".equals(name_tag)
							|| "STORE".equals(name_tag)
							|| "IMAGE".equals(name_tag)
							|| "GOODS".equals(name_tag)) {
						string_map = new LinkedHashMap<String, String>();
					}
					if (string_map != null) {
						for (int i = 0; i < params.length; i++) {
							if (params[i].equals(name_tag)) {
								// 若为null，则置为""
								temp_string = pullParser.nextText();
								string_map.put(params[i], temp_string);
							}
						}
					}

					break;
				case XmlPullParser.END_TAG:
					if ("TRANDETAIL".equals(pullParser.getName())
							||"ORGPOSTERIMAGE".equals(pullParser.getName())
							|| "STORE".equals(pullParser.getName())
							|| "IMAGE".equals(pullParser.getName())
							|| "GOODS".equals(pullParser.getName())) {// 判断结束标签元素是否是book
						String key, value = "";
						for (Map.Entry<String, String> entry : string_map.entrySet()) {
							key = entry.getKey();
							// 若为null，则置为""
							value = (entry.getValue() == null) ? "" : entry.getValue();
							value = (!"".equals(value)) ? value.trim() : value;
							string_map.put(key, value);
						}
						list_map.add(string_map);
						string_map = null;
					}

					break;
				}
				event = pullParser.next();
			}

			// 解析得到map合集
			return list_map;
		} catch (Exception e) {
			KLog.e(TAG, e.getMessage() + "");
		}
		return null;
	}


	/**
	 * @param inputStream 输入流
	 * @param params	  xml节点数组   new String[] { "TRMMODNO", "TXNCD", "PICTURE" };
	 * @return List<Map<String, String>>
	 */
	public static List<Map<String, String>> parser(InputStream inputStream, String[] params) {
		if (inputStream == null || params == null) {
			return null;
		}

		List<Map<String, String>> list_map = new ArrayList<Map<String, String>>();
		Map<String, String> string_map =  null;

		try {
			XmlPullParser pullParser = Xml.newPullParser();
			pullParser.setInput(inputStream, "UTF-8");
			int event = pullParser.getEventType();

			while (event != XmlPullParser.END_DOCUMENT) {
				switch (event) {

				case XmlPullParser.START_DOCUMENT:
					break;

				case XmlPullParser.START_TAG:

					String name_tag = pullParser.getName();
					if ("TRANDETAIL".equals(name_tag)
							||"ORGPOSTERIMAGE".equals(pullParser.getName())) {
						string_map = new LinkedHashMap<String, String>();
//						pullParser.getAttributeValue(0);
					}
					if (string_map != null) {
						for (int i = 0; i < params.length; i++) {
							if (params[i].equals(name_tag)) {
								string_map.put(params[i], pullParser.nextText());
							}
						}
					}

					break;
				case XmlPullParser.END_TAG:
					if ("TRANDETAIL".equals(pullParser.getName())
							||"ORGPOSTERIMAGE".equals(pullParser.getName())) {// 判断结束标签元素是否是book
						list_map.add(string_map);
						string_map = null;
					}

					break;
				}
				event = pullParser.next();
			}

			// 解析得到map合集
			return list_map;
		} catch (Exception e) {
			KLog.e(TAG, e.getMessage() + "");
		}
		return null;
	}

	/**
	 * 解析XML转换成对象
	 *
	 * @param is 输入流
	 * @param clazz 对象Class
	 * @param fields 字段集合一一对应节点集合
	 * @param elements 节点集合一一对应字段集合
	 * @param itemElement 每一项的节点标签
	 * @return list
	 */
	public static List<Object> parser(InputStream is, Class<?> clazz,
			List<String> fields, List<String> elements, String itemElement) {

		List<Object> list = new ArrayList<Object>();
		try {
			XmlPullParser xmlPullParser = Xml.newPullParser();
			xmlPullParser.setInput(is, "UTF-8");
			int event = xmlPullParser.getEventType();

			Object obj = null;

			while (event != XmlPullParser.END_DOCUMENT) {
				switch (event) {
				case XmlPullParser.START_TAG:
					if (itemElement.equals(xmlPullParser.getName())) {
						obj = clazz.newInstance();
					}
					if (obj != null && elements.contains(xmlPullParser.getName())) {
						setFieldValue(obj, fields.get(elements.indexOf(xmlPullParser.getName())),
								xmlPullParser.nextText());
					}
					break;
				case XmlPullParser.END_TAG:
					if (itemElement.equals(xmlPullParser.getName())) {
						list.add(obj);
						obj = null;
					}
					break;
				}
				event = xmlPullParser.next();
			}
		} catch (Exception e) {
			Log.e("rss", "解析XML异常：" + e.getMessage());
			throw new RuntimeException("解析XML异常：" + e.getMessage());
		}
		return list;
	}

	/**
	 * 设置字段值
	 * @param propertyName 字段名
	 * @param obj 实例对象
	 * @param value 新的字段值
	 * @return
	 */
	public static void setFieldValue(Object obj, String propertyName,
			Object value) {
		try {
			Field field = obj.getClass().getDeclaredField(propertyName);
			field.setAccessible(true);
			field.set(obj, value);
		} catch (Exception ex) {
			throw new RuntimeException();
		}
	}
}
